package com.lineage.server.serverpackets;

import com.lineage.server.datatables.sql.MailTable;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.templates.L1Mail;
import java.util.ArrayList;
import java.util.Iterator;

public class S_Mail extends ServerBasePacket {
  private static final String S_MAIL = "[S] S_Mail";
  
  private byte[] _byte;
  
  public S_Mail(L1PcInstance pc, int type) {
    this._byte = null;
    ArrayList<L1Mail> mails = new ArrayList<>();
    Iterator<L1Mail> iterator = MailTable.get().getAllMail().iterator();
    while (iterator.hasNext()) {
      L1Mail mail = iterator.next();
      if (mail.getInBoxId() == pc.getId() && mail.getType() == type)
        mails.add(mail); 
    } 
    if (mails.isEmpty())
      return; 
    writeC(186);
    writeC(type);
    writeH(mails.size());
    int i = 0;
    while (i < mails.size()) {
      L1Mail mail2 = mails.get(i);
      writeD(mail2.getId());
      writeC(mail2.getReadStatus());
      writeD((int)(mail2.getDate().getTime() / 1000L));
      writeC(mail2.getSenderName().equalsIgnoreCase(pc.getName()) ? 1 : 0);
      writeS(mail2.getSenderName().equalsIgnoreCase(pc.getName()) ? mail2.getReceiverName() : 
          mail2.getSenderName());
      writeByte(mail2.getSubject());
      i++;
    } 
  }
  
  public S_Mail(L1PcInstance pc, int mailId, boolean isDraft) {
    this._byte = null;
    L1Mail mail = MailTable.get().getMail(mailId);
    writeC(186);
    writeC(80);
    writeD(mailId);
    writeC(isDraft ? 1 : 0);
    writeS(pc.getName());
    writeByte(mail.getSubject());
  }
  
  public S_Mail(int type, boolean isDelivered) {
    this._byte = null;
    writeC(186);
    writeC(type);
    writeC(isDelivered ? 1 : 0);
  }
  
  public S_Mail(int mailId, int type) {
    this._byte = null;
    switch (type) {
      case 48:
      case 49:
      case 50:
      case 64:
        writeC(186);
        writeC(type);
        writeD(mailId);
        writeC(1);
        return;
    } 
    L1Mail mail = MailTable.get().getMail(mailId);
    if (mail != null) {
      writeC(186);
      writeC(type);
      writeD(mail.getId());
      writeByte(mail.getContent());
    } 
  }
  
  public byte[] getContent() {
    if (this._byte == null)
      this._byte = getBytes(); 
    return this._byte;
  }
  
  public String getType() {
    return "[S] S_Mail";
  }
}
